package com.atguigu.sugar.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.sugar.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController //标记是controller
public class SugarController {

    @Autowired // 自动注入
    ProductService product;
    @RequestMapping("/sugar/gmv") // requstmapping既可以get,又能post
    public String gmv(@RequestParam(value = "date",defaultValue = "0") int date){
        date = checkDate(date);
        // 获取数据
        BigDecimal gmv = product.gmv(date);
        JSONObject result = new JSONObject();

        result.put("data",gmv);
        result.put("status",0);
        result.put("msg","");
        return  result.toJSONString();
    }

    @RequestMapping("/sugar/gmv/c3") //
    public String gmvByC3(@RequestParam(value = "date",defaultValue = "0") int date){
        date = checkDate(date);
        // 获取数据
        List<Map<String, Object>> list = product.gmvByC3(date);
        JSONObject result = new JSONObject();
        result.put("status",0);
        result.put("msg","");

        JSONObject data = new JSONObject();
        JSONArray categories = new JSONArray();
        data.put("categories",categories);
        for (Map<String, Object> map : list) {
            Object c3Name = map.get("category3_name");
            categories.add(c3Name);
        }
        JSONArray series = new JSONArray();
        JSONObject obj = new JSONObject();
        obj.put("name","商品品类");
        JSONArray data1 = new JSONArray();
        for (Map<String, Object> map : list) {
            data1.add(map.get("order_amount"));
        }
        obj.put("data",data1);

        series.add(obj);


        data.put("series",series);
        result.put("data",data);
        return  result.toJSONString();
    }

    private int checkDate(int date) {
        if (date ==0) { //表示没有传递日期
            date = Integer.parseInt( new SimpleDateFormat("yyyyMMdd").format(new Date()));
        }
        return date;
    }

}
